package net.ibizsys.eclipse.studio.util;

import java.util.HashMap;
import java.util.Map;

import net.ibizsys.eclipse.studio.api.CallResult;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

/**
 * 
 * @author <a href='http://www.weibo.com/xjtoo' target='_blank'>Enmaai</a>
 */
public class HTTPKit
{
	private static HttpClient httpclient = null;
	private static HashMap<String, String> header = null;
	static
	{
		if (httpclient == null)
		{
			httpclient = new HttpClient();
		}
		if (header == null)
		{
			header = new HashMap<String, String>();
			header.put("Content-Type", "application/x-www-form-urlencoded");
			header.put("User-Agent", "ibizsys/eclipse-studio");
		}
	}

	/**
	 * POST请求数据
	 * 
	 * @param url 地址
	 * @param params 参数
	 * @return
	 * @throws Exception
	 */
	public static CallResult post(String url, Map<String, String> params)
	{
		if (StringKit.IsBlank(url))
		{
			return new CallResult(-1, "");
		}
		PostMethod method = new PostMethod(url);

		for (String key : header.keySet())
		{
			method.setRequestHeader(key, header.get(key));
		}
		try
		{
			if (params != null && params.size() > 0)
			{
				NameValuePair[] param = new NameValuePair[params.size()];

				int index = 0;
				for (String key : params.keySet())
				{
					String value = params.get(key);
					if (StringKit.IsBlank(value))
					{
						value = "";
					}
					param[index++] = new NameValuePair(key, value);
				}
				method.setRequestBody(param);
			}

			int nStatusCode = httpclient.executeMethod(method);

			if (nStatusCode == 200)
			{

				return new CallResult(0, null, method.getResponseBodyAsString());
			} else
			{
				return new CallResult(-1, "网络请求错误[" + nStatusCode + "]");
			}
		} catch (Exception ex)
		{
			return new CallResult(-1, "网络请求异常");
		}
	}
}
